﻿
using System;
using System.Collections.Generic;
using Reflector;
using Reflector.CodeModel;



public class SortPakage : IPackage
{

    private IAssemblyManager assemblyManager;
    private ICommandBarManager commandBarManager;
    private ICommandBarSeparator separator;
    private ICommandBarButton button;

    public void Load(IServiceProvider serviceProvider)
    {
        this.assemblyManager = (IAssemblyManager)serviceProvider.GetService(typeof(IAssemblyManager));
        this.commandBarManager = (ICommandBarManager)serviceProvider.GetService(typeof(ICommandBarManager));
        this.separator = this.commandBarManager.CommandBars["Tools"].Items.AddSeparator();
        this.button = this.commandBarManager.CommandBars["Tools"].Items.AddButton("Order Assembly &List", new EventHandler(this.OrderAssemblyListButton_Click));
    }
    
    public void Unload()
    {
        this.commandBarManager.CommandBars["Tools"].Items.Remove(this.button);
        this.commandBarManager.CommandBars["Tools"].Items.Remove(this.separator);
    }

    private void OrderAssemblyListButton_Click(object sender, EventArgs e)
    {
        IAssemblyCollection assemblies = this.assemblyManager.Assemblies;
        SortedList<string, IAssembly> newAssemblyOrder = new SortedList<string, IAssembly>();

        // Add to new SortedList
        foreach (IAssembly assembly in assemblies)
        {
            newAssemblyOrder.Add(assembly.Name, assembly);
        }
        
        // Remove each item and add in order
        foreach (KeyValuePair<string, IAssembly> item in newAssemblyOrder)
        {
            assemblies.Remove(item.Value);
            assemblies.Add(item.Value);
        }
    }
}
